<?php

namespace app\user\controller;

use \app\check\controller\Check;
use app\common\cachemodel\Article;
use app\common\cachemodel\Recode;
use app\common\model\Article as ArticleModel;
use app\common\model\ArticleCollect;
use think\Cache;
use \think\Db;

// 用户中心
class Userinfo extends Check
{
    /**
     * 获取用户信息
     * @return json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function get()
    {
        $user = Db::table('app_user')
            ->field('id,tel,nickname,avatar,forbidden,uc_id,sex,has_self_recode')
            ->where('id', $this->user['id'])->find();
        if (empty($user))
        {
            return json(['code' => 10208, 'msg' => 'User is not exist.']);
        } else
        {
            return json(['code' => 200, 'data' => $user]);
        }
    }

    /**
     * 禁用用户
     * @return json
     */
    public function denied_user()
    {
        $result = Db::table('app_user')->where('id', $this->user['id'])->save(['forbidden' => 1]);

        if (!$result)
        {
            return json(['code' => 10209, 'msg' => 'Failed to denied user.']);
        } else
        {
            return json(['code' => 200, 'msg' => 'Success to denied user.']);
        }
    }

    /**
     * 取消首次登陆标记
     */
    public function not_first_login()
    {
        $result = Db::table('app_user')->where('id', $this->user['id'])->save(['is_first_login' => 0]);

        if (!$result)
        {
            return json(['code' => 10210, 'msg' => 'Failed to do it.']);
        } else
        {
            return json(['code' => 200, 'msg' => 'Success to do it.']);
        }
    }

    /**
     * 更新用户信息
     */
    public function edit()
    {
        $data['id'] = input('id/d');
        if (!$data['id'])
        {
            return json(['code' => 10211, 'msg' => 'User is not exist.']);
        }
//        $data['username'] = htmlspecialchars(input('username'));
//        $data['password'] = htmlspecialchars(input('password'));
//        if($data['password'] && strlen($data['password']) != 32)
//        {
//            return json(['code'=>10042,'msg' => 'User is not exist.']);
//        }
        $data['nickname'] = htmlspecialchars(input('nickname'));
        $data['sex'] = (int)(input('sex'));
        $data['avatar'] = htmlspecialchars(input('avatar'));
//        $data['email'] = htmlspecialchars(input('email'));
        $data['birthday'] = (int)(input('birthday'));
        $data['province'] = htmlspecialchars(input('province'));
        $data['city'] = htmlspecialchars(input('city'));
//        $data['job_id'] = htmlspecialchars(input('job_id'));
        $data['url_token'] = htmlspecialchars(input('url_token'));
        $data['default_timezone'] = htmlspecialchars(input('default_timezone'));

        $result = Db::table('app_user')->where('id', $this->user['id'])->update($data);

        if (!$result)
        {
            return json(['code' => 10212, 'msg' => 'Failed to do it.']);
        } else
        {
            return json(['code' => 200, 'msg' => 'Success to do it.']);
        }
    }

    public function save_sex()
    {
        $user['sex'] = input('param.sex/d');

        $recode['type'] = input('param.sex/d');

        $RecodeModel = new Recode();
        try
        {
            Db::table('app_user')->where('id', $this->user['id'])->update($user);
            $recode_info = $RecodeModel->getRecodeLists($this->user['id'], 1);
            $RecodeModel->UpdateData($this->user['id'], $recode_info['id'], $recode);
//            $result = Db::table('app_recode')->where($where)->update($recode);
        }
        catch (\Exception $e)
        {
            return show(config('code.error'), 'Failed to do it.');
        }

        $this->rm_cache();
        return json(['code' => 200, 'msg' => 'Success to do it.']);
    }

    //保存头像
    public function save_avatar()
    {
        $data['avatar'] = htmlspecialchars(input('param.avatar/s'));

        $result = Db::table('app_user')->where('id', $this->user['id'])->update($data);

        if (!$result)
        {
            return json(['code' => 10212, 'msg' => 'Failed to do it.']);
        } else
        {
            $this->rm_cache();
            return json(['code' => 200, 'msg' => 'Success to do it.']);
        }
    }

    public function save_nickname()
    {
        $data['nickname'] = htmlspecialchars(input('nickname/s', ''));

        if (trim($data['nickname']) == '')
        {
            return json(['code' => 10211, 'msg' => 'User is not exist.']);
        }

        $result = Db::table('app_user')->where('id', $this->user['id'])->update($data);

        if (!$result)
        {
            return json(['code' => 10212, 'msg' => 'Failed to do it.']);
        } else
        {
            $this->rm_cache();
            return json(['code' => 200, 'msg' => 'Success to do it.']);
        }
    }

    /**
     * 用户认证
     * @return mixed
     */
    public function verified()
    {

        return json(['code' => 200, 'msg' => 'Success.']);
    }

    /**
     * 我的收藏
     * @throws \Exception
     */
    public function my_collect()
    {
        $data_is_from_cache = 1;//是否从缓存获取数据
        if ($data_is_from_cache)
        {
            $data = (new ArticleCollect())->getUserCollectPage($this->user['id'],1);
            return show(config('code.success'), '获取成功', $data);
        } else
        {//没加缓存之前的写法
            $data = Db::table('wechatadmin.system_article')->alias('a')
                ->field('a.id,a.title,a.introduction,ac.create_time,a.cid')
                ->join('wechatadmin.system_article_collect ac', 'a.id=ac.aid')
                ->where(['ac.ucid' => $this->user['uc_id'], 'a.status' => 1])
                ->order('ac.create_time DESC')
                ->paginate(10, false, ['query' => request()->param()]);

            return json(['code' => 200, 'data' => $data, 'msg' => 'Success.']);
        }

    }

    /**
     * 我赞过的
     */
    public function my_good()
    {
        $data_is_from_cache = 1;//是否从缓存获取数据
        if ($data_is_from_cache)
        {
            if (!request()->isPost())
            {
                return show(config('code.error'), '未知操作', [], 403);
            }
            //当前请求哪一页的数据
            $page = input('post.page/d', 1);

            //获取用户点赞文章的所有id
            $map = ['uid' => $this->user['id'], 'ucid' => $this->user['uc_id']];
            $cache = (new ArticleModel())->getUserArticleGood($map, 1);
            $aids = $cache['ids'];
            $times = $cache['times'];

            $per_page = 10;//每页显示数量
            $aids = explode(',', $aids);//将$aids转换为数组
            $times = explode(',', $times);//将$times转换为数组
            array_shift($aids);//去除数组第一个元素
            array_shift($times);//去除数组第一个元素
            $aids = array_reverse($aids);//把aid倒序
            $times = array_reverse($times);//把文章的点赞时间倒序
            $total = count($aids);//统计有多少个id
            $data_list = getPaginatorData($total, $page, $per_page);//获取数据分页信息
            $aids = array_slice($aids, $data_list['start'], $per_page);//获取分页后的文章id数组
            $times = array_slice($times, $data_list['start'], $per_page);//获取分页后的文章id数组

            unset($data_list['start']);
            unset($data_list['end']);

            //根据id获取所有的文章数据
            foreach ($aids as $index => $aid)
            {
                $article = (new ArticleModel())->getArticleDetails($this->user['id'], ['id' => $aid, 'is_old' => true], 0);
                if ($article)
                {
                    unset($article['content']);
                    unset($article['author']);
                    unset($article['avatar']);
                    unset($article['thumb']);
                    unset($article['publish_time']);
                    unset($article['good']);
                    unset($article['collect']);
                    unset($article['read']);
                    unset($article['type_name']);
                    unset($article['type_name_en']);
                    unset($article['is_hot']);
                    unset($article['read_delay']);
                    $article['create_time'] = $times[$index];//赋值点赞时间
                    $data_list['data'][] = $article;
                }
            }

            return json(['code' => 200, 'data' => $data_list, 'msg' => 'Success.']);
        } else
        {//没加缓存之前的写法
            $data = Db::table('wechatadmin.system_article')->alias('a')
                ->field('a.id,a.title,a.introduction,ag.create_time,a.cid')
                ->join('wechatadmin.system_article_good ag', 'a.id=ag.aid')
                ->where(['ag.ucid' => $this->user['uc_id'], 'a.status' => 1])
                ->order('ag.create_time DESC')
                ->group('a.id')
                ->paginate(10, false, ['query' => input('param.page')]);

            return json(['code' => 200, 'data' => $data, 'msg' => 'Success.']);
        }

    }

    public function rm_cache()
    {
        // 修改用户信息时,删除用户信息缓存
        Cache::rm('userinfo:' . $this->user['id']);
    }

}
